package main

import (
	"fmt"
	"math/rand"
)

func main() {
	fmt.Println("--------arr1--------")
	arr1()
	fmt.Println("--------arr2--------")
	arr2()
	fmt.Println("--------arr3--------")
	arr3()
	fmt.Println("--------rangeArr--------")
	rangeArr()
	fmt.Println("--------arrCopy--------")
	arrCopy()
	fmt.Println("--------sumArr--------")
	var a2 [11]int
	for i := 0; i < len(a2); i++ {
		// 产生一个 0 到 1000 随机数
		a2[i] = rand.Intn(1000)
	}
	sum := sunArr(a2)
	fmt.Printf("sunArr:%d\n", sum)
}

func arr1() {
	a := [3]int{1, 2, 3}
	b := [...]int{1, 2, 3}
	c := [5]int{1, 2, 3, 4, 5}
	d := [5]string{"a", "b", "c", "d"}
	e := [4]string{1: "a", 2: "b", 3: "c"}
	f := [...]struct {
		name string
		age  uint
	}{
		{"a", 1},
		{"b", 2},
	}
	fmt.Println(a, b, c, d, e, f)
}
func arr2() {
	a1 := [5][2]int{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}}
	var a2 [2][3]int = [...][3]int{{1, 2, 3}, {7, 8, 9}}
	var a3 [5][3]int
	fmt.Println(a1, a2, a3)
}

// 数组值拷贝性能问题，通常用slice或者指针
func arr3() {
	arr4 := [2]int{}
	fmt.Printf("arr4: %p\n", &arr4)
	arr5 := test(arr4)
	fmt.Println("arr4:", arr4)
	fmt.Println("arr5:", arr5)
}

func test(x [2]int) (y [2]int) {
	fmt.Printf("x:%p\n", &x)
	x[1] = 1000
	y = x
	return
}

func rangeArr() {
	var arr6 [2][3]int = [...][3]int{{1, 2, 3}, {4, 5, 6}}
	for k1, v1 := range arr6 {
		fmt.Printf("%d ,%v\n", k1, v1)
		for k2, v2 := range v1 {
			fmt.Printf("(%d,%d)=%d\n", k1, k2, v2)
		}
		fmt.Println()
	}
}

// 数组拷贝和传参
func arrCopy() {
	var arr6 [5]int
	printArr(&arr6)
	fmt.Println(arr6)
	var arr7 = [5]int{1, 2, 3, 4, 5}
	printArr(&arr7)
}

func printArr(arr *[5]int) {
	arr[0] = 10
	for i, v := range arr {
		fmt.Println(i, v)
	}
}

// 元素求和
func sunArr(a [11]int) int {
	var sum int = 0
	for i := 0; i < len(a); i++ {
		sum = sum + a[i]
	}
	return sum
}
